package logic

import (
	"context"
	"house/models/mysql"
	"time"

	"house/houserpc/houserpc"
	"house/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HouseListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHouseListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HouseListLogic {
	return &HouseListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HouseListLogic) HouseList(in *houserpc.HouseListRequest) (*houserpc.HouseListResponse, error) {
	// todo: add your logic here and delete this line
	offset := (in.Page - 1) * in.Size
	var house []mysql.House
	px := mysql.DB.Debug().Offset(int(offset)).Limit(int(in.Size))
	if in.PriceOrder == 1 {
		px = px.Order("houses.price desc")
	}
	if in.PriceOrder == 2 {
		px = px.Order("houses.price asc")
	}
	if in.TimeOrder == 1 {
		px = px.Order("houses.created_at desc")
	}
	if in.TimeOrder == 2 {
		px = px.Order("houses.created_at asc")
	}
	px.Find(&house)
	var b []*houserpc.HouseList
	for _, c := range house {
		list := houserpc.HouseList{
			HouseId:   int64(c.ID),
			UserId:    int64(c.UserId),
			Title:     c.Title,
			Price:     float32(c.Price),
			Rent:      float32(c.Rent),
			Area:      int64(c.Area),
			City:      c.City,
			Way:       c.Way,
			StartTime: c.CreatedAt.Format(time.DateTime),
		}
		b = append(b, &list)
	}
	return &houserpc.HouseListResponse{
		List: b,
	}, nil
}
